﻿
using NP.BPMReportPlatform.AUTO;
using NP.BPMReportPlatform.AUTO.Adjust.Dto;
using NP.BPMReportPlatform.AUTO.Quotation.Dto;
using NP.BPMReportPlatform.AUTO.TechnicalDependence.Dto;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Engine;
using NP.BPMReportPlatform.CommonEnum;
using NP.BPMReportPlatform.FlowManagement.Dto;
using NP.BPMReportPlatform.IC.ICZHYLS.Dto;
using NP.BPMReportPlatform.IUTS.Dto;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.IUTS
{
   public class ProductComplaintsAppService : BPMReportPlatformAppService, IProductComplaintsAppService
    {
        private readonly SqlSugarClient _db, _dbEngine;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sqlSugarAppService"></param>
        public ProductComplaintsAppService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp, IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbEngine = sqlSugarAppService.GetEngineInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        #region  
        /// <summary>
        /// 获取Queryable
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<IUTSOutput> GetQueryable(GetIUTSInput input)
        {

            var listQueryable = _db.Queryable<IUCustomerComplaintsHeader, BusinessProcessesNew, IUCustomerComplaintsDetails>(
                    (x, bu,d1) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == bu.InstanceId, JoinType.Left,  x.InstanceNumber == d1.InstanceNumber))
                
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    (x, bu, d1) => x.InstanceNumber.Contains(input.InstanceNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Equals(input.AddUserName))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, bu) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), bu.ProcessStatusName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.BusinessDivision), x => x.BusinessDivision.Equals(input.BusinessDivision))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Area), x => x.Area.Equals(input.Area))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Company), x => x.Company.Equals(input.Company))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProcessName), x => x.ProcessName.Equals(input.ProcessName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProductName), (x, bu, d1) => d1.ProductName.Contains(input.ProductName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.BatchNumber), (x, bu, d1) => d1.BatchNumber.Contains(input.BatchNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName), x => x.CustomerName.Contains(input.CustomerName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime && x.AddTime.AddDays(-1) <= input.EndCreationTime)

                .Select((x, bu, d1) =>
                    new IUTSOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        BusinessDivision = x.BusinessDivision,
                        Company = x.Company,
                        ProcessName = x.ProcessName.Replace("CreateProductComplaints", "质量原因投诉").Replace("CreateElseComplaints", "非质量原因投诉"),
                        BusinessDivisionType = x.BusinessDivisionType,
                        Area = x.Area,
                        CustomerName = x.CustomerName,
                        CustomerNo = x.CustomerNo,
                        ProductName = d1.ProductName,
                        AbnormalType = d1.AbnormalType,
                        BatchNumber = d1.BatchNumber,
                        OrderStatus = bu.ProcessStatusName,
                        CreateTime = bu.StartTime.ToString(),
                        UserName = bu.StartUserName,

                    }).MergeTable().Distinct().OrderBy(ins => ins.InstanceNumber, OrderByType.Desc);

            return listQueryable;
        }





        /// <summary>
        /// 更新表单状态(将InstanceStates中的最新状态更新到BusinessProcessesNew)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //private async Task UpdateOrderStatus(GetIUTSInput input)
        //{
        //    var listQueryableFormEngine = await _dbEngine.Queryable<Instances, InstanceStates, Activities, BpmTask>((i, ins, a, t) => new JoinQueryInfos(JoinType.Inner, i.InstanceId == ins.InstanceId,
        //       JoinType.Left, i.InstanceId == a.InstanceId && a.Status == 1,
        //       JoinType.Left, a.ActivityId == t.ActivityId))
        //      .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), i => i.Number.Contains(input.InstanceNumber))
        //      .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), i => i.StartUserName.Equals(input.AddUserName))
        //      .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, (i, ins) => ins.StartTime >= input.StartCreationTime && ins.StartTime <= input.EndCreationTime)

        //      .Select((i, ins, a, t) =>
        //      new GetProcessInfoOutput()
        //      {
        //          InstanceNumber = i.Number,
        //          Topic = i.Topic,
        //          StartUserName = i.StartUserName,
        //          StartTime = ins.StartTime,
        //          LatestActivityName = ins.LatestActivityName,
        //          Status = ins.Status,
        //          StatusName = ins.StatusName,
        //          ActivityResolverName = t.ActivityResolverName
        //      }).MergeTable().Distinct().OrderBy(ins => ins.StartTime, OrderByType.Desc).ToListAsync();

        //    var listQueryable = await _db.Queryable<IUCustomerComplaintsHeader, BusinessProcessesNew>(
        //            (x, bu) => new JoinQueryInfos(
        //                JoinType.Left, x.InstanceNumber == bu.InstanceId))


        //            .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
        //            (x, bu) => x.InstanceNumber.Contains(input.InstanceNumber))

        //        .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Equals(input.AddUserName))
        //        .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, bu) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), bu.ProcessStatusName))
        //        //.WhereIF(!string.IsNullOrWhiteSpace(input.RequirmentType), x => x.RequirmentType.Equals(input.RequirmentType))
        //        //.WhereIF(!string.IsNullOrWhiteSpace(input.Trade1), x => x.Trade1.Equals(input.Trade1))
        //        .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime && x.AddTime.AddDays(-1) <= input.EndCreationTime)

        //        .Select((x, bu) =>
        //            new BusinessProcessesNew()
        //            {
        //                BusinessProcessId = bu.BusinessProcessId,
        //                InstanceId = bu.InstanceId,
        //                Type = bu.Type,
        //                ProcessId = bu.ProcessId,
        //                ProcessTopic = bu.ProcessTopic,
        //                StartTime = bu.StartTime,
        //                ProcessStartUserId = bu.ProcessStartUserId,
        //                StartUserName = bu.StartUserName,
        //                ProcessStatus = bu.ProcessStatus,
        //                ProcessStatusCode = bu.ProcessStatusCode,
        //                ProcessStatusName = bu.ProcessStatusName,
        //                AddTime = bu.AddTime,
        //                LatelyActivityName = bu.LatelyActivityName,
        //                BusinessType = bu.BusinessType,
        //                BusinessTypeName = bu.BusinessTypeName,
        //                IsEnd = bu.IsEnd,
        //                FinishTime = bu.FinishTime
        //            }).MergeTable().Distinct().OrderBy(bu => bu.InstanceId, OrderByType.Desc).ToListAsync();

        //    listQueryable.ForEach(async x =>
        //    {
        //        var statusName = listQueryableFormEngine.Where(e => e.InstanceNumber == x.InstanceId).FirstOrDefault()?.StatusName;
        //        if (!string.IsNullOrEmpty(statusName) && x.ProcessStatusName != statusName)
        //        {
        //            //更新BusinessProcessesNew表单状态
        //            x.ProcessStatusName = statusName;
        //            //await _db.Updateable<BusinessProcessesNew>(x).ExecuteCommandAsync();
        //            await _db.Updateable<BusinessProcessesNew>()
        //           .SetColumns(x => new BusinessProcessesNew { ProcessStatusName = statusName })
        //           .Where(u => u.InstanceId == x.InstanceId)
        //           .ExecuteCommandAsync();
        //        }
        //    });
        //}

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<IUTSOutput>> GetAllAsync(GetIUTSInput input)
        {
            ////await UpdateOrderStatus(input);
            RefAsync<int> totalCount = 0;
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);

            });



            //返回结果
            return new PagedResultDto<IUTSOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }




        #endregion
 

        #region IU投诉报表导出GetQueryableExport1

        private ISugarQueryable<ExportIUTSOutput> GetQueryableExport1(GetIUTSInput input)
        {

            var listQueryable = _db.Queryable<IUCustomerComplaintsHeader, BusinessProcessesNew, IUCustomerComplaintsDetails, IUCustomerComplaintsCorrectives, IUCustomerComplaintsSchemes>(
                    (x, bu, d1, d2, d3) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == bu.InstanceId,
                    JoinType.Left, x.InstanceNumber == d1.InstanceNumber, JoinType.Left, x.InstanceNumber == d2.InstanceNumber, JoinType.Left, x.InstanceNumber == d3.InstanceNumber))


                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber), (x, bu, d1, d2, d3) => x.InstanceNumber.Contains(input.InstanceNumber))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Equals(input.AddUserName))
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, bu) => SqlFunc.ContainsArray<string>(input.OrderStatus.ToArray(), bu.ProcessStatusName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.BusinessDivision), x => x.BusinessDivision.Equals(input.BusinessDivision))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Area), x => x.Area.Equals(input.Area))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Company), x => x.Company.Equals(input.Company))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProcessName), x => x.ProcessName.Equals(input.ProcessName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CustomerName), x => x.CustomerName.Contains(input.CustomerName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.ProductName), (x, bu, d1) => d1.ProductName.Contains(input.ProductName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.BatchNumber), (x, bu, d1) => d1.BatchNumber.Contains(input.BatchNumber))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime && x.AddTime.AddDays(-1) <= input.EndCreationTime)

                .Select((x, bu, d1, d2, d3) =>
                    new ExportIUTSOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        BusinessDivision = x.BusinessDivision,
                        Company = x.Company,
                        ProcessName = x.ProcessName.Replace("CreateProductComplaints", "质量原因投诉").Replace("CreateElseComplaints", "非质量原因投诉"),
                        BusinessDivisionType = x.BusinessDivisionType,
                        Area = x.Area,
                        CustomerName = x.CustomerName,
                        CustomerNo = x.CustomerNo,
                        ProductType = x.ProductType,
                        RiskRank = x.RiskRank,
                        ProductType1 = d1.ProductType,
                        productName = d1.ProductName,
                        AbnormalType = d1.AbnormalType,
                        BatchNumber = d1.BatchNumber,
                        productNetWeight = d1.productNetWeight,
                        ProductNumber = d1.ProductNumber,
                        ProductWeight = d1.ProductWeight,
                        //productName = d1.ProductName,
                        CustomerRank = x.CustomerRank,
                        SumWeight = x.SumWeight,
                        SumWeightRank = x.SumWeightRank,
                        IsNoReappear = x.IsNoReappear,
                        ExceptionCase = x.ExceptionCase,
                        MeasureOrEffect = x.MeasureOrEffect,
                        CauseAnalyse = x.CauseAnalyse,
                        DisposeScheme = x.DisposeScheme,
                        OverCase = x.OverCase,
                        IsCorrectiveEffective = x.IsCorrectiveEffective,
                        Remark = x.Remark,
                        ZRRtext = x.ZRRtext,
                        JZYFffirmResult = x.JZYFffirmResult,
                        ComplaintsTime = x.ComplaintsTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        PBffirmResult = x.PBffirmResult,
                        PBffirmIdea = x.PBffirmIdea,
                        SellAffirmResult = x.SellAffirmResult,
                        Department = x.Department,
                        ResponsiblePersonCode = x.ResponsiblePersonCode,
                        TwoCause = x.TwoCause,
                        SellAffirmIdea = x.SellAffirmIdea,
                        SchemeId = d3.SchemeId,
                        ImplementationDept = d3.ImplementationDept,
                        ImplementationPerson = d3.ImplementationPerson,
                        Completion = d3.Completion,
                        CorrectiveId = d2.CorrectiveId,
                        CorrectiveMeasure = d2.CorrectiveMeasure,
                        OrderStatus = bu.ProcessStatusName,
                        CreateTime = bu.StartTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        UserName = bu.StartUserName,
                        //LatelyActivityName = bu.,
                        FinishTime = bu.FinishTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),


                    }).MergeTable().Distinct().OrderBy(ins => ins.InstanceNumber, OrderByType.Desc);

            return listQueryable;
        }
 
        #endregion

        #region IU投诉报表导出Export1Async
        /// <summary>
        /// 报表导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<ExportIUTSOutput>> Export1Async(GetIUTSInput input)
        {
            //await UpdateOrderStatus(input);
            RefAsync<int> totalCount = 0;
            var listQueryable = GetQueryableExport1(input);
            var listViewDto = await listQueryable.ToListAsync();
            //var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);



            var i = 1;
            listViewDto.ForEach(x => x.SerialNumber = i++.ToString());
            return listViewDto;
        }
 
        #endregion
    }
}
